<template>
  <div>
    <h1>{{id ? '编辑' : '新建'}}广告位</h1>
    <el-form label-width="120px" :model="ads" @submit.native.prevent="save">
      <el-form-item label="广告位商品">
        <el-autocomplete
          class="inline-input"
          v-model="state"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      ads: {},
      goods: [],
      state: "",
    };
  },
  methods: {
    async fetch() {
      const res = await this.$http.get(`rest/goods`);
      this.goods = res.data
    },
    async categoryFetch() {
      await this.$http.get(`rest/categories`);
    },
    async save() {
      if (this.id) {
        await this.$http.put(`rest/ads/${this.id}`, this.ads);
      } else {
        await this.$http.post("rest/ads", this.ads);
      }
      this.$router.push("/ads/list");
      this.$message({
        message: "保存成功",
        type: "success"
      });
    },
    querySearch(queryString, cb) {
      var goods = this.goods
      goods.map(item => {
        item.value = item.name
      })
        var results = queryString
        ? goods.filter(this.createFilter(queryString))
        : goods;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return goods => {
        return (
          goods.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },

    handleSelect(item) {
      console.log(item);
      this.ads = {
        name: item.name,
        image: item.pic[0].url,
        url: item._id
      }
    }
  },
  created() {
    this.categoryFetch();
  },
  mounted() {
    this.fetch();
  },
};
</script>
<style scoped>
</style>